#!/bin/bash
CMAKE_PARAMS=""

WORKDIR=${WORKDIR/D:/\/d}
WORKDIR=${WORKDIR//\\/\/}
TEST_SUITE_DIR=${TEST_SUITE_DIR/D:/\/d}
TARGET=aarch64-linux-hos
DISABLED_TESTS="FFmpeg;CLAMR;LMbench;GCC-C-execute-complex-5"

echo "Currently in ${WORKDIR}"
mkdir ${TARGET}
cd ${TARGET}
echo "###### Compilation for ${TARGET} ######"
echo "Currently in ${WORKDIR}/${TARGET}"
echo "Using ${CLANG_TOOLCHAIN} and ${TEST_SUITE_DIR}"

if [[ ${TEST_SUITE_SUBDIRS} ]]; then
    echo "Compiling follow subdirs: '${TEST_SUITE_SUBDIRS}'"
    CMAKE_PARAMS+=" -DTEST_SUITE_SUBDIRS='${TEST_SUITE_SUBDIRS}'"
fi

echo "'${DISABLED_TESTS}' are disabled"
CMAKE_PARAMS+=" -DDISABLED_TESTS='${DISABLED_TESTS}'"

echo "Configuring with CMake"
(set -x; 
/usr/bin/cmake -DCMAKE_C_COMPILER=${WORKDIR}/${CLANG_TOOLCHAIN}/bin/clang.exe \
               -DCMAKE_CXX_COMPILER=${WORKDIR}/${CLANG_TOOLCHAIN}/bin/clang++.exe \
               ${TEST_SUITE_DIR} \
               -DTOOLCHAIN_OUT=${WORKDIR}/${CLANG_TOOLCHAIN} \
               -DSYSROOT_OUT=${WORKDIR}/sysroot \
               -DCMAKE_TOOLCHAIN_FILE:FILEPATH=${TEST_SUITE_DIR}/cmake/caches/CompilerSettingsHOS.cmake \
               -DTEST_SUITE_BUILD_TARGET=${TARGET} \
               -DCMAKE_C_COMPILER_DIRECTORY=${WORKDIR}/${CLANG_TOOLCHAIN}/bin \
               -DCMAKE_C_FLAGS=-O3 -DTEST_SUITE_COLLECT_COMPILE_TIME=OFF \
               ${CMAKE_PARAMS}
) || cmake_code=$?
cp CMakeFiles/CMakeOutput.log ${WORKDIR}/res_cmake_output_${TARGET}.log
cp CMakeFiles/CMakeError.log ${WORKDIR}/res_cmake_error_${TARGET}.log

if [[ "${cmake_code}" -ne 0 ]]; then
    echo "Error: CMake configuring for ${TARGET} has failed! Please, check log in artifacts" >>  ${WORKDIR}/job_result.txt
else
    echo "Compiling... Invoking make"
    (set -x; /usr/bin/make -k -j 10 VERBOSE=1 all 1> >(tee -a ${WORKDIR}/res_make_output_${TARGET}.txt) 2> >(tee -a ${WORKDIR}/res_make_error_${TARGET}.txt >&2)) || make_code=$? 
    if [[ "${make_code}" -ne 0 ]]; then
        echo "Error: Compilation for ${TARGET} has failed! Please, check log in artifacts" >>  ${WORKDIR}/job_result.txt
    else 
        echo "!!! Compilation for ${TARGET} finished successfully !!! But better check job console log, just in case" >>  ${WORKDIR}/job_result.txt
    fi
fi
cd ${WORKDIR}
